package com.alibaba.csp.sentinel.dashboard.rule;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

/**
 * AbstractDynamicRuleService
 *
 * @author kancy
 * @date 2020/5/4 15:59
 */
public abstract class AbstractDynamicRuleService<T> implements DynamicRuleService<List<T>> {
    /**
     * 规则序列化
     * @param rules
     * @return
     */
    protected String serialize(List<T> rules){
        return JSON.toJSONString(rules, true);
    }

    /**
     * 反序列化规则
     * @param rules
     * @return
     */
    protected List<T> deserialize(String rules){
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return JSON.parseArray(rules, getGenericType());
    }

    /**
     * 获取泛型类
     * @return
     */
    private Class getGenericType() {
        return (Class) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
}
